const mongo = require('../db/db.js')
const formidable = require('formidable')
const time = require('../../util/time.js')
const getId = require('../../util/getId.js')
module.exports = {
    addLink:function (req,res) {
        let form = new formidable.IncomingForm();
        form.parse(req,function (err,files,file) {
            let typename = files.name;
            let url = files.url;
            getId.getId('linkId',function (id) {
                mongo.insert('link',{name:typename,url:url,time:time.time(),id:id},function () {
                    res.json({
                        status:200,
                        msg:'增加成功'
                    })
                })
            });


        })
    },
    findLink:function (req,res) {
        mongo.find('link',{},{id:-1},function (result) {
            res.json({
                status:200,
                msg:result
            })
        })
    },
        editLink:function (req,res) {
        let id =  parseInt(req.query.id);
        let name = req.query.name;
        let url = req.query.url;
       mongo.update('link',{'id':id},{$set:{name:name,url:url,time:time.time()}},function () {
           res.json({
               status:200,
               msg:'更改成功'
           })
       })
    },
    deleteLink:function (req,res) {
        let id =  parseInt(req.query.id);
        mongo.del('link',{"id":id},function () {
            res.json({
                status:200,
                msg:'删除成功'
            })
        })
    },
    deleteMany:function (req,res) {
        let ids = req.query.ids.split(',');
        var index = 0
        for(let i=0;i<ids.length;i++){
            let id = parseInt(ids[i])
            mongo.del('link',{"id":id},function () {
                index++;
                if(index==ids.length-1){
                    res.json({
                        status:200,
                        msg:'删除成功'
                    })
                }

            })
        }

    }
}
